local skynet = require "skynet"
local redis = require 'skynet.db.redis'

--把table转为字符串
function table_to_str(obj)
    local lua = ""  
    local t = type(obj)  
    if t == "number" then  
        lua = lua .. obj  
    elseif t == "boolean" then  
        lua = lua .. tostring(obj)  
    elseif t == "string" then  
        lua = lua .. string.format("%q", obj)  
    elseif t == "table" then  
        lua = lua .. "{"  
        for k, v in pairs(obj) do  
            lua = lua .. "[" .. table_to_str(k) .. "]=" .. table_to_str(v) .. ","  
        end  
        local metatable = getmetatable(obj)  
        if metatable ~= nil and type(metatable.__index) == "table" then  
            for k, v in pairs(metatable.__index) do  
                lua = lua .. "[" .. table_to_str(k) .. "]=" .. table_to_str(v) .. ","  
            end  
        end  
        lua = lua .. "}"  
    elseif t == "nil" then  
        return nil  
    else  
        error("can not serialize a " .. t .. " type.")  
    end  
    return lua
end

--把字符串转为table
function str_to_table(table_str)
    if table_str == nil or type(table_str) ~= "string" then
        return
    end
    return load("return " .. table_str)()
end

-- 启动服务器
function start_server()
    print("==========Redis Test Start=========")
    --配置redis节点信息
    local config = { host = '127.0.0.1', port = 6379, db = 0 }

	--连接redis数据库
    local db = redis.connect(config)

	--设置key-value
    --保存字符串
    db:set('name1','imdt_student1')
    db:set('name2','imdt_student2')
    --保存table
    local tb = {a=100, b=200, c={a=1,b=2}}
    db:set("table1", table_to_str(tb))


	--获取之前设置的key-value
    print('redis value name1: ', db:get('name1'))
    print('redis value name2: ', db:get('name2'))
    print('redis value name3: ', db:get('name3'))

    tb = str_to_table(db:get("table1"))
    print(table_to_str(tb))

    --存盘
    function save_db()
        print("save db---")
        db:save()   -- db:bgsave()
        skynet.timeout(100, save_db)    --10秒后执行save_db
    end
    save_db()
end

-- 启动服务器
skynet.start(start_server)

